package com.luoqy.speedy.data;


import java.util.concurrent.*;

import javax.sql.DataSource;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import com.luoqy.speedy.SpeedyApplication;
import com.luoqy.speedy.common.FirstCreateBase;
import com.zaxxer.hikari.HikariDataSource;

import lombok.Data;
/**
 * 数据库配置管理
 * @author lumberer
 * @date 2020年7月29日
 */
@Configuration
@ConfigurationProperties(prefix="")
@PropertySource(value = {"file:${jdbcConfigPath}"}, encoding="utf-8")
@Data
public class DataBase {
	/**
	 * 账号
	 */
	private String account;
	/**
	 * 密码
	 */
	private String password;
	/**
	 * 链接地址
	 */
	private String url;
	/**
	 * 驱动
	 */
	private String driverClass;
	/**
	 * 默认读取数据配置
	 * */
	@Bean
	public DataSource dataSources(){
		HikariDataSource dataSource=new HikariDataSource();
		dataSource.setJdbcUrl(url);
		dataSource.setUsername(account);
		dataSource.setPassword(password);
		dataSource.setDriverClassName(driverClass);
		dataSource.setMinimumIdle(50);
		return dataSource;
		
	}
	
	/**
	 * 重启服务重新加载数据配置
	 */
	public static boolean RestartService(){
		try {
			ExecutorService service =new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
	   		service.execute(new Runnable() {
					@Override
					public void run() {
					// TODO Auto-generated method stub
						SpeedyApplication.context.close();
						SpeedyApplication.context=SpringApplication.run(SpeedyApplication.class, SpeedyApplication.args);
						if(SpeedyApplication.context.isRunning()){
							FirstCreateBase.init();
						}else{
							try {
								Thread.sleep(3000);
								FirstCreateBase.init();
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							
						}
						
					}    
				});
	   		service.shutdown();
			System.err.println("Spring.application.name:"+SpeedyApplication.appName);
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return false;
		}
		
	}
	
  //配置第一个数据源  多数据源配时
//    @Bean(name = "primaryDataSource")
//    @Qualifier("primaryDataSource")
//    @ConfigurationProperties(prefix="alert.spring.datasource.primary")
//    public DataSource primaryDataSource() {
//        return DataSourceBuilder.create().build();
//    }

    //配置第二个数据源
/* @Bean(name = "secondaryDataSource")
    @Qualifier("secondaryDataSource")
    @Primary
    @ConfigurationProperties(prefix="alert.spring.datasource.secondary")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }*/
 
}
